import { defineComponent, PropType } from 'vue';
import { useNamespace } from '@ibiz-template/vue3-util';
import { ISearchBarFilter, ISearchBarGroup } from '@ibiz/model-core';
import { IFilterNodeItems, IFilterNodeField } from '@ibiz-template/runtime';
import { FilterSearchBarController } from '../../filter-search-bar.controller';
import FilterItem from '../filter-item/filter-item';

/**
 * 过滤分组组件
 * - 绘制系统定义的过滤器
 */
export const FilterGroup = defineComponent({
  name: 'FilterGroup',
  props: {
    data: {
      type: Object as PropType<IFilterNodeItems>,
      required: true,
    },
    model: {
      type: Object as PropType<ISearchBarGroup>,
      required: true,
    },
    controller: {
      type: Object as PropType<FilterSearchBarController>,
      required: true,
    },
  },
  emits: ['change'],
  setup(props, { emit }) {
    const ns = useNamespace('filter-group');
    const c = props.controller;
    const searchBarFilters: ISearchBarFilter[] = [];

    /**
     * 初始化子项模型
     *
     */
    const initChildrenModel = (): void => {
      if (props.data.children.length > 0) {
        props.data.children.forEach(child => {
          const item = c.model.searchBarFilters?.find(
            filter =>
              filter.appDEFieldId?.toLowerCase() ===
              (child as IFilterNodeField).field,
          );
          if (item) {
            searchBarFilters.push(item);
          }
        });
      }
    };

    initChildrenModel();

    /**
     * 过滤条件变化
     *
     * @param {IData} item
     */
    const onChange = (item: IData): void => {
      emit('change', item);
    };

    /**
     * 绘制子条件项
     *
     * @return {*}  {JSX.Element[]}
     */
    const renderContent = (): JSX.Element[] => {
      return searchBarFilters.map((model, index) => {
        return (
          <FilterItem
            data={props.data.children[index] as IFilterNodeField}
            model={model}
            controller={props.controller}
            onChange={onChange}
          ></FilterItem>
        );
      });
    };

    return {
      ns,
      renderContent,
    };
  },
  render() {
    return <div class={this.ns.b()}>{this.renderContent()}</div>;
  },
});
export default FilterGroup;
